package com.cs456.TeamBobcat;

import java.io.IOException;
import java.sql.Date;

import com.cs456.TeamBobcat.database.Constants;
import com.cs456.TeamBobcat.database.MyDB;
import com.cs456.TeamBobcat.database.MyDBhelper;

import android.app.ListActivity;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class WhatDidTheySayHistory extends ListActivity {
	
	protected static final String LOG_TAG = "RecentAudio";
	MyDB dba;
	private String[] AUDIO;
	private String[] mFileName;	
	private Long[] mDate;
	private MediaPlayer mPlayer = null;


	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

		dba = new MyDB(this);
        dba.open();
        
        initAudio();
        
        dba.close();
        setListAdapter(new ArrayAdapter<String>(this, R.layout.audiohistory, AUDIO));

        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            	mPlayer = new MediaPlayer();
            	try {
            		mPlayer.setDataSource(mFileName[position]);
            		mPlayer.prepare();
            		mPlayer.start();
            		Date dt = new Date(mDate[position]);
            	    Toast.makeText(getApplicationContext(), android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss", dt),
            	              Toast.LENGTH_SHORT).show();
        		} catch (IOException e) {
        			Log.e(LOG_TAG, "prepare() failed");
        		}
              
            }
          });

	}
	
	private void initAudio() {
		
    	Cursor prevAudio = dba.getAudio();
    	int i=0;
    	AUDIO= new String[prevAudio.getCount()];
    	mFileName= new String[prevAudio.getCount()];
    	mDate = new Long[prevAudio.getCount()];
    	prevAudio.moveToFirst();
        while (prevAudio.isAfterLast() == false) {
        	int index1 = prevAudio.getColumnIndex(Constants.AUDIO_TEXT);
        	int index2 = prevAudio.getColumnIndex(Constants.AUDIO_PATH);
        	int index3 = prevAudio.getColumnIndex(Constants.DATE_NAME);
            AUDIO[i] = prevAudio.getString(index1);
            mFileName[i] = prevAudio.getString(index2);
            mDate[i] = prevAudio.getLong(index3);
            i++;
          	prevAudio.moveToNext();
          	}

	}
}
